package com.zznj.xzjc.activity;

import android.Manifest;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxDeviceTool;
import com.vondear.rxtool.view.RxToast;
import com.zznj.xzjc.MainActivity;
import com.zznj.xzjc.R;
import com.zznj.xzjc.base.BaseActivity;
import com.zznj.xzjc.net.SharedHelper;
import com.zznj.xzjc.net.entity.BaseBean;
import com.zznj.xzjc.net.entity.LoginBean;
import com.zznj.xzjc.net.rxjava.HttpMethods;
import com.zznj.xzjc.net.subscribers.ProgressSubscriber;
import com.zznj.xzjc.net.subscribers.SubscriberOnNextListener;
import com.zznj.xzjc.permission.MPermission;
import com.zznj.xzjc.permission.annotation.OnMPermissionDenied;
import com.zznj.xzjc.permission.annotation.OnMPermissionGranted;
import com.zznj.xzjc.permission.annotation.OnMPermissionNeverAskAgain;
import com.zznj.xzjc.push.ExampleUtil;
import com.zznj.xzjc.utils.Code;
import com.zznj.xzjc.utils.StringUtils;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import okhttp3.FormBody;


/**
 * Created by JY on 2017/11/15.
 */

public class LoginActivity extends BaseActivity {
    private static final String TAG = "LoginActivity";
    /**
     * 基本权限管理
     */
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private final int BASIC_PERMISSION_REQUEST_CODE = 110;


    @BindView(R.id.et_login_name)
    EditText et_login_name;
    @BindView(R.id.et_login_password)
    EditText et_login_password;
    @BindView(R.id.forget_password)
    TextView forget_password;
    @BindView(R.id.btn_login)
    TextView btn_login;
    @BindView(R.id.et_yzm)
    TextView et_yzm;
    @BindView(R.id.iv_showCode)
    ImageView iv_showCode;

    //查看
    @BindView(R.id.lookImg)
    ImageView lookImg;
    //产生的验证码
    private String realCode;




    @Override
    protected int getLayoutId() {
        return R.layout.activity_login_layout;
    }

    @Override
    public void initView() {
        back.setVisibility(View.GONE);
        requestBasicPermission();

        //将验证码用图片的形式显示出来
        iv_showCode.setImageBitmap(Code.getInstance().createBitmap());
        realCode = Code.getInstance().getCode().toLowerCase();
    }

    private void requestBasicPermission() {
        MPermission.with(LoginActivity.this).setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS).request();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        et_login_name.setText(SharedHelper.readValueByKeyForString(mContext,"mobile"));
//        et_login_password.setText(SharedHelper.readValueByKeyForString(mContext, "password"));
    }

    private boolean look = false;
    @OnClick({R.id.lookImg,R.id.btn_login,R.id.iv_showCode})
    public void onViewClicked(View view) {
        if(view.getId() == R.id.lookImg){
            if(look){
                look = false;
                et_login_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                lookImg.setImageResource(R.mipmap.gyss_biyan_img);
            }else{
                look = true;
                et_login_password.setInputType(InputType.TYPE_CLASS_TEXT);
                lookImg.setImageResource(R.mipmap.gyss_kankan_img);
            }
        }else if (view.getId() == R.id.btn_login) {
            String mobile = et_login_name.getText().toString();
            String password = et_login_password.getText().toString();
            String yzm = et_yzm.getText().toString();
            if (StringUtils.isEmpty(mobile)) {
                RxToast.normal("请输入手机号");
                return;
            }
            if (StringUtils.isEmpty(password)) {
                RxToast.normal("请输入密码");
                return;
            }
//            if(StringUtils.isEmpty(yzm)){
//                RxToast.normal("请输入验证码");
//                return;
//            }
//            if(StringUtils.isEmpty(yzm)){
//                RxToast.normal("请输入验证码");
//                return;
//            }

//            if (!yzm.toLowerCase().equals(realCode)) {
//                RxToast.normal("验证码错误");
//                return;
//            }
            login(mobile, password);
        }else if(view.getId() == R.id.iv_showCode){
            iv_showCode.setImageBitmap(Code.getInstance().createBitmap());
            realCode = Code.getInstance().getCode().toLowerCase();
            Log.v(TAG,"realCode"+realCode);
        }
    }

    private String registrationID;
    @Override
    protected void initData() {
        String appKey = ExampleUtil.getAppKey(getApplicationContext());
        registrationID = JPushInterface.getRegistrationID(mContext);
        if(StringUtils.isEmpty(registrationID)){
            registrationID = JPushInterface.getRegistrationID(mContext);
        }
    }

    /**
     * 登录
     * @param mobile
     * @param pwd
     */
    private void login(final String mobile, final String pwd) {
        SubscriberOnNextListener<BaseBean<LoginBean>> onNextListener = baseBean -> {
            RxToast.normal(baseBean.getMessage());
            SharedHelper.saveKeyValueForString(mContext,"mobile",mobile);
            SharedHelper.saveKeyValueForString(mContext,"password",pwd);
            SharedHelper.saveKeyValueForString(mContext,"Member",new Gson().toJson(baseBean.getResult()));

            RxActivityTool.skipActivity(mContext, MainActivity.class);
        };
        //post方式提交的数据
        FormBody formBody = new FormBody.Builder()
                .add("username", mobile)
                .add("password", pwd)
                .add("deviceCode", registrationID)
                .build();
        Log.i("deviceId：",RxDeviceTool.getIMEI(this));
        HttpMethods.getInstance().login(new ProgressSubscriber<>(onNextListener, LoginActivity.this, true), formBody);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {
        // 权限获取成功！
    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionFailed() {
        // 权限获取失败！
    }
}
